from typing import List

from server.app.cloud_ide.schema.users.request.user_create_request import UserCreateRequest
from server.app.cloud_ide.schema.users.request.user_role_update_request import UserRoleUpdateRequest
from server.app.cloud_ide.schema.users.request.user_update_password_request import UserUpdatePassWordRequest
from server.app.cloud_ide.schema.users.request.user_update_request import UserUpdateRequest
from server.app.cloud_ide.schema.users.response.user_detail_entity import UserDetailEntity
from server.app.cloud_ide.schema.users.response.user_list_entity import UserListEntity
from server.app.cloud_ide.service.tenant_service import TenantService
from server.framework.core.logger import logger
from server.framework.core.settings import settings
from server.framework.utils.keycloak_manager import build_keycloak_admin, build_keycloak_client


class UserService:

    def list_users(self) -> List[UserListEntity]:

        user_list: List[UserListEntity] = []
        keycloak_admin = build_keycloak_admin()
        users = keycloak_admin.get_users()
        tenant_service = TenantService()
        for user in users:
            user_groups = keycloak_admin.get_user_groups(user_id=user['id'])
            for i in user_groups:
                tenant = tenant_service.get_tenant_by_name(i['path'].split('/')[1])
                i['tenant_name'] = tenant.name
                i['tenant_id'] = tenant.id
            entity = UserListEntity(
                id=user['id'],
                username=user['username'],
                enabled=user['enabled'],
                first_name=user['firstName'],
                last_name=user['lastName'],
                email=user['email'],
                groups=user_groups
            )
            user_list.append(entity)

        return user_list

    def create_user(self, data: UserCreateRequest) -> bool:
        try:
            keycloak_admin = build_keycloak_admin()
            keycloak_admin.create_user(payload={
                "email": data.email,
                "username": data.username,
                "enabled": True,
                "firstName": data.first_name,
                "lastName": data.last_name,
                "credentials": [
                    {
                        "value": data.password,
                        "type": "password",
                    }
                ]
            }, exist_ok=False)
            return True
        except Exception as e:
            logger.error(f'新增用户[{data.username}]失败,异常信息:[{e}]')
            return False

    def find_user_by_name(self, user_name):
        users = self.list_users()
        target_user = None
        for x in users:
            if x.username == user_name:
                target_user = x
                break
        return target_user

    def get_user_detail(self, user_id: str) -> UserDetailEntity:
        keycloak_admin = build_keycloak_admin()
        user_info = keycloak_admin.get_user(user_id)
        user_groups = keycloak_admin.get_user_groups(user_id)
        tenant_service = TenantService()
        is_admin = False
        for i in user_groups:
            tenant = tenant_service.get_tenant_by_name(i['path'].split('/')[1])
            i['tenant_name'] = tenant.name
            i['tenant_id'] = tenant.id
            if i['path'] == settings.admin_group_path:
                is_admin = True
        entity = UserDetailEntity(
            id=user_id,
            username=user_info['username'],
            first_name=user_info['firstName'],
            last_name=user_info['lastName'],
            email=user_info['email'] if 'email' in user_info else '',
            groups=user_groups,
            is_admin=is_admin
        )
        return entity

    def update_user_info(self, data: UserUpdateRequest) -> bool:
        try:
            keycloak_admin = build_keycloak_admin()
            payload = {
                "email": data.email,
                "enabled": True,
                "firstName": data.first_name,
                "lastName": data.last_name,
            }
            keycloak_admin.update_user(user_id=data.id, payload=payload)
            return True
        except Exception as e:
            logger.error(f'编辑用户[{data.id}]失败,异常信息:[{e}]')
            return False

    def delete_users(self, delete_user_ids: list) -> bool:
        try:
            keycloak_admin = build_keycloak_admin()
            for user_id in delete_user_ids:
                # 此处为临时处理逻辑
                user_detail = self.get_user_detail(user_id)
                if user_detail.username != 'ailab':
                    keycloak_admin.delete_user(user_id=user_id)
            return True
        except Exception as e:
            logger.error(f'删除用户[{delete_user_ids}]失败,异常信息:[{e}]')
            return False

    def set_user_roles(self, data: UserRoleUpdateRequest) -> bool:
        try:
            keycloak_admin = build_keycloak_admin()
            user_groups = keycloak_admin.get_user_groups(data.id)
            for user_group in user_groups:
                keycloak_admin.group_user_remove(data.id, user_group['id'])
            if data.group_id != '':
                groups = data.group_id.split(',')
                for group in groups:
                    keycloak_admin.group_user_add(data.id, group)
            return True
        except Exception as e:
            logger.error(f'设置用户角色[{data}]失败,异常信息:[{e}]')
            return False

    def change_password(self, data: UserUpdatePassWordRequest):
        if data.operator_is_admin is False:
            try:
                user_detail = self.get_user_detail(data.id)
                keycloak_client = build_keycloak_client()
                keycloak_client.token(
                    username=user_detail.username, password=data.password,
                )
            except Exception as e:
                logger.error(f'修改用户[{user_detail}]失败,用户密码不匹配,异常信息:[{e}]')
                return False
        try:
            keycloak_admin = build_keycloak_admin()
            keycloak_admin.set_user_password(user_id=data.id, password=data.new_password,
                                             temporary=data.need_renew)
            return True
        except Exception as e:
            logger.error(f'修改用户[{data.id}]失败,异常信息:[{e}]')
            return False
